package com.grsu.TransportSystem.controllers;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.grsu.TransportSystem.domain.Person;
import com.grsu.TransportSystem.services.PersonService;
import com.grsu.TransportSystem.validators.CreatePersonValidator;

@Controller
public class PersonController {

	@Autowired
	CreatePersonValidator createPersonValidator;

	@InitBinder
	private void initBinder(WebDataBinder binder) {
		binder.setValidator(createPersonValidator);
	}

	@Autowired
	PersonService personService;

	@RequestMapping(value = "/getCreateUserForm")
	public String getCreateTripForm() {
		return "createUser";
	}

	@RequestMapping(value = "/createUser")
	public ModelAndView createTrip(@ModelAttribute(value = "person") @Valid Person person, BindingResult result, ModelMap model) {

		String resultMessage = null;

		if (result.hasErrors()) {
			resultMessage = "createuser.fail";
		} else {
			personService.createPerson(person);
			model.addAttribute("message", "User " + person.getName()
					+ " is created");
			resultMessage = "createuser.success";
		}

		return new ModelAndView("createUser", "message", resultMessage);
	}

}
